export default {
	namespaced:true,//使用命名空间
	state:{//共享的数据
		cart:JSON.parse(uni.getStorageSync('cart') || '[]')
	},
	mutations:{//操作共享数据的方法
		//添加商品到购物车
		addToCart(state,goods){
			// 根据提交的商品的Id，查询购物车中是否存在这件商品
			// 如果不存在，则 findResult 为 undefined；否则，为查找到的商品信息对象
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(!findResult){
				state.cart.push(goods)
			}else{
				//如果有，则将该商品数量加1
				findResult.goods_count++
			}
			//通过commit方法，调用m_cart命名空间下的saveCartToStorage方法
			this.commit('my_cart/saveCartToStorage')
		},
		saveCartToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateCart(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_state = goods.goods_state
				this.commit('my_cart/saveCartToStorage')
			}
		},
		updateNum(state,goods){
			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
			if(findResult){
				findResult.goods_count = goods.goods_count
				this.commit('my_cart/saveCartToStorage')
			}
		},
		deleteGoodsById(state,goods_id){
			state.cart = state.cart.filter(x => x.goods_id !== goods_id)
			this.commit('my_cart/saveCartToStorage')
		},
		updateAllState(state,newState){
			state.cart.forEach(x => x.goods_state = newState)
			this.commit('my_cart/saveCartToStorage')
		}
	},
	getters:{//相当于computed计算属性
		total(state){
			// let c = 0
			// state.cart.forEach(x => {
			// 	c += x.goods_count
			// })
			// return c
			return state.cart.reduce((total,item) => total += item.goods_count,0)
		},
		//计算要结算的商品数量
		settleCount(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count,0)
		},
		//计算结算的总金额
		settlePrice(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
		}
	}
}